<?php
class UserAdminAction extends Action{
	public function index(){
        $this->validate();
        $storeModel = D("store");
        $vo = $storeModel->field('store_index,suser_pointcard,store_color,store_id')->join("suser on suser.suser_id = store.store_mid")
        ->where("suser.suser_id='".$_SESSION['suser']['account']."'")->find();
        $this->assign("result", $vo['store_index']); 
        $this->assign("color", $vo['store_color']); 
        $this->assign("id", $vo['store_id']);
        $this->assign("pointcard", $vo['suser_pointcard']);
        $this->display('index'); 
    }
    
     //显示首页编辑器
     public function index_edit(){
		$this->validate();
        $storeModel = D("Store");
        $vo = $storeModel->field('store_index,suser_pointcard')->join("suser on suser.suser_id = store.store_mid")
        ->where("suser.suser_id='".$_SESSION['suser']['account']."'")->find();
        $this->assign("result", $vo['store_index']);
        $this->assign("pointcard", $vo['suser_pointcard']);
	    $this->display();
     }
     
     //编辑首页
     public function edit_index(){
        $this->validate();
        import("@.ORG.Input");
        $Store = D('Store');
        $data['store_index'] = Input::getVar($_POST['content']);
        if(false!==$Store->where("store_id='".$_SESSION['suser']['store_id']."'")->save($data)){
            $this->redirect('UserAdmin/index');
        }else{
            echo "修改失败，原因：".$Store->getDbError();
        }
     }
     
     //显示
     public function merchandise(){
        $this->validate();
        import("@.ORG.Input");
        $level = Input::getVar($_GET['level']);
        $id = empty($_GET['id'])?0:Input::getVar($_GET['id']);
        $condition['mcd_sid'] = $_SESSION['suser']['store_id'];
        $condition['mcd_level'] = $level;
        $condition['mcd_mid'] = $id;
        $Merchandise = D('Merchandise');
        $count = $Merchandise->where($condition)->count();
        $vo = $Merchandise->where($condition)->select();
        foreach($vo as $key=>&$value){
            $value['mcd_activenum'] = (int)((date('U')-strtotime($value['mcd_update']))/86400+1);
        }
        $condition['mcd_hiddenflag'] = 0;
        $count2 = $Merchandise->where($condition)->count();
        $hiddenflagall = $count-$count2;
        $this->assign("vo", $vo);
        $this->assign("count", $count);
        $this->assign("hiddenflagall", $hiddenflagall);
        $this->assign("level",$level);
        $this->assign("id",$id);
	    $this->display();
     }
     
	public function filter($var)
	{
        if($var == '')
        {
                return false;
        }

        return true;
	}

	//登陆信息验证
	public function validate(){
		if(empty($_SESSION['suser'])){
			$this->redirect('Index/index');
		}
	}
    
    //更新商品详细
	public function updateDetail(){
        $this->validate();
        $this->upload();
    }
    
    //更新店铺详细
	public function updateStoreDetail(){
        $this->validate();
        if(!empty($_POST['store_id'])){
            import("@.ORG.Input");
            $storeModel = D("store");
            $data['store_detail'] =Input::getVar($_POST['store_detail']);
        	if(false!==$storeModel->where("store_id='".trim($_POST['store_id'])."'")->save($data)){
			    $this->ajaxReturn($data,'更新商品详细成功！',1);
            }
        }
    }
    
     //编辑店铺背景色
     public function updateColorForStore(){
        $this->validate();
        import("@.ORG.Input");
        $store = D('store');
        $data['store_color'] = Input::getVar($_POST['color']);
        if(false!==$store->where("store_id = '".Input::getVar($_POST['id'])."'")->save($data)){
            $this->ajaxback('','更新背景色成功！',1);
        }else{
             $this->ajaxback($data,$store->getLastSql().'更新背景色失败！',0);
        }
     }
     
     //编辑文件背景色
     public function updateColorForDetail(){
        $this->validate();
        import("@.ORG.Input");
        $merchandise = D('merchandise');
        $data['mcd_color'] = Input::getVar($_POST['color']);
        if(false!==$merchandise->where("mcd_id = '".Input::getVar($_POST['id'])."'")->save($data)){
            $this->ajaxback('','更新背景色成功！',1);
        }else{
             $this->ajaxback($data,$merchandise->getLastSql().'更新背景色失败！',0);
        }
     }
	
	//添加商品
	public function addCommodity(){
		$this->validate();
        import("@.ORG.Input");
        $count = Input::getVar($_GET['count']);
		$level = trim($_GET['level']);
        $id = trim($_GET['id']);

		if(!empty($count) && !empty($level) && !is_null($id)){
			$merchandiseModel = D("merchandise");
			for($i=0;$i<$count;$i++){
				$data = array();
				$data['mcd_sid'] = $_SESSION['suser']['store_id'];
				$data['mcd_update'] = date("Y-m-d H:i:s");
                $data['mcd_level'] = $level;
                $data['mcd_mid'] = $id;
				$merchandiseModel->add($data);
			}
            
            $vo = $merchandiseModel->field("mcd_id,mcd_itemno,mcd_title,mcd_activenum,mcd_hiddenflag")->where("mcd_sid='".$_SESSION['suser']['store_id']."'")->select();
            $this->ajaxback($vo,$merchandiseModel->getLastSql(),1);
		}else{
			$vo = "";
		    $this->ajaxback($_GET,'参数出错',0);
		}
	}
    
    //输出ajax结果
    
    private function ajaxback($data,$msg,$states){
        $result = array(
            'data' => $data,
            'msg' => $msg,
            'states' => $states
        );
        echo json_encode($result);
    }
	
	//删除商品
	public function deleteCommodity(){
		$this->validate();
		$id = trim($_GET['id']);
		if(!empty($id)){
			$merchandiseModel = D("merchandise");
			$result	=	$merchandiseModel->where("mcd_id='".$id."'")->delete();
			if(false !== $result) {
                $this->ajaxback($id,'删除成功！',1);
			}else{
                $this->ajaxback($id,'删除出错!',0);
			}
		}else{
			$this->ajaxback('','删除商品系列失败，请重试！',0);
		}
		
	}
    
	//隐藏文件
	public function hideCommodity(){
		$this->validate();
		$id = trim($_POST['id']);
        $id = explode(",",$id);
        $flag = trim($_POST['flag']);
		if(!empty($id)){
			$merchandiseModel = D("merchandise");
            $data['mcd_hiddenflag'] = $flag;
            $condition['mcd_id'] = array('in',$id);
			$result	=	$merchandiseModel->where($condition)->save($data);
			if(false !== $result) {
                $this->ajaxback($id,'设置成功！',1);
			}else{
                $this->ajaxback($id,'设置出错!',0);
			}
		}else{
			$this->ajaxback('','设置文件系列失败，请重试！',0);
		}
		
	}
    
	//隐藏此层全部文件
	public function hideCommodityall(){
		$this->validate();
		$id = trim($_POST['id']);
        $level = trim($_POST['level']);
        $flag = trim($_POST['flag']);
		if(!is_null($id)){
			$merchandiseModel = D("merchandise");
            $data['mcd_hiddenflag'] = $flag;
            $condition['mcd_mid'] = $id;
            $condition['mcd_level'] = $level;
			$result	=	$merchandiseModel->where($condition)->save($data);
			if(false !== $result) {
                $this->ajaxback($id,'设置成功！',1);
			}else{
                $this->ajaxback($id,'设置出错!',0);
			}
		}else{
			$this->ajaxback('','设置文件系列失败，请重试！',0);
		}
		
	}
	
	//显示商品信息
	public function merchandise_detail(){
		$this->validate();
		$this->getmerchandise("merchandise_detail");
	}
    
    private function getmerchandise($tpl){
		if(!empty($_GET['id'])){
			$merchandise =D("merchandise");
            $suserModel = D("suser");
			$mcd = $merchandise->where("mcd_id='".trim($_GET['id'])."'")->find();
            $pointcard = $suserModel->field("suser_pointcard")->where("suser_id='".$_SESSION['suser']['account']."'")->find();
			$this->assign("vo",$mcd);
            $this->assign("color",$mcd['mcd_color']);
            $this->assign("url",$tpl=="merchandise_edit"?'merchandise_detail/id/'.$_GET['id']:'merchandise/level/'.$mcd['mcd_level']);
            $this->assign("pointcard",$pointcard['suser_pointcard']);
            $this->assign("id",$_GET['id']);
			$this->display($tpl);
		}else{
			$this->redirect('index');
		}
    }
	
	//验证激活
	public function checkActive(){
		$this->validate();
		if(!empty($_POST['id'])){
			$merchandiseModel = D('merchandise');
			$result = $merchandiseModel->where("mcd_id='".trim($_POST['id'])."'")->find();
			if($result!==null){
				$hour = (date('U')-strtotime($result['mcd_update']))/3600;
				$data['hour'] = $hour;
				$data['id'] = trim($_POST['id']);
				if($hour<168 && $result['mcd_activenum']!=0){
					$this->ajaxback($data,'时间不足168小时无需激活！',0);
				}else{
					$this->ajaxback($result,'超过168小时需激活！',1);
				}
			}else{
				$this->ajaxback($data,'当前商品不存在！',2);
			}
		}else{
			$this->ajaxback($data,'参数出错，请重试！',2);
		}
	}
	
	//激活货架
	public function active(){
		$this->validate();
		$suserModel = D('suser');
		$merchandiseModel = D('merchandise');
		$result = $suserModel->field("suser_pointcard")->where("suser_id='".$_SESSION['suser']['account']."'")->find();
		if($result!==null){
			if($result['suser_pointcard']<=0){
				$this->ajaxback("",'点额数不足，不能激活货品，请先充值再激活！',0);
			}else{
				$data['suser_pointcard'] = $result['suser_pointcard']-1;
				$suserModel->startTrans();
				if(false !==$suserModel->where("suser_id='".$_SESSION['suser']['account']."'")->save($data)){
					$resultMerchandise = $merchandiseModel->field("mcd_activenum")->where("mcd_id='".$_POST['id']."'")->find();
					if($resultMerchandise!==null){
						$dataMerchandise['mcd_activenum'] = $resultMerchandise['mcd_activenum']+1;
						//date_default_timezone_set (PRC);
						$dataMerchandise['mcd_update'] = date('Y-m-d H:i:s');
						if(false !==$merchandiseModel->where("mcd_id='".$_POST['id']."'")->save($dataMerchandise)){
							$suserModel->commit();
							$this->ajaxback($data['suser_pointcard'],'货品激活成功！',1);
						}else{
							$suserModel->rollback();
							$this->ajaxback($merchandiseModel->getDbError(),'激活货品失败，请重试1！',0);
						}
					}else{
						$suserModel->rollback();
						$this->ajaxback('','激活货品失败，请重试2！',0);
					}
				}else{
					$suserModel->rollback();
					$this->ajaxback('','激活货品失败，请重试3！',0);
				}
				
			}
		}
		else{
			$this->ajaxback($result['suser_pointcard'],'参数问题激活货品失败，请重试！',0);
		}
	}
	
	//图片上传
	public function upload(){
			if(!empty($_FILES)) {
			//如果有文件上传 上传附件
			//dump($_FILES);
			$this->_upload();
		}
	}
	
	protected function _upload()
    {

       
        import("@.ORG.UploadFile");
        import("@.ORG.Input");
        $upload = new UploadFile();
        //设置上传文件大小
        $upload->maxSize  = 300000;
        //设置上传文件类型
        $upload->allowExts  = explode(',','jpg,gif,png,jpeg');
        //设置附件上传目录
        $upload->savePath =  './Public/Uploads/';
	   //设置上传文件规则
	   $upload->saveRule = uniqid;
	   //删除原图
	   $upload->thumbRemoveOrigin = false;
       if(!empty($_FILES['logo'])){  
            if(!$upload->upload()) {
                //捕获上传异常
            	if(isset($_POST['_uploadResponse'])) {
                    $uploadSuccess =  0;
                    $ajaxMsg  =  $upload->getErrorMsg();
                }else {
                    //捕获上传异常
                    $ajaxMsg = $upload->getErrorMsg();                
                }
            }else {
                //取得成功上传的文件信息
                $savename = $upload->getUploadFileInfo();
          ;
                $uploadSuccess    =    1;
                //$this->ajaxUploadResult("asd");
                //dump($uploadList);
            }
       }else{
           $uploadSuccess    =    2;
       }
        if(!empty($_POST['meid'])&&$uploadSuccess!=0){
	        $merchandiseModel = D("merchandise");
	        $data = Array();
            if($uploadSuccess==1){
	            $data["mcd_logo"] = $savename[0]['savename'];
            }
            $data["mcd_itemno"] = Input::safeHtml(Input::addSlashes(Input::getVar($_POST['itemno'])));
            $data["mcd_title"] = Input::safeHtml(Input::addSlashes(Input::getVar($_POST['title'])));
            $data["mcd_mid"] = Input::safeHtml(Input::addSlashes(Input::getVar($_POST['title'])));
	    	if(false!==$merchandiseModel->where("mcd_id='".trim($_POST['meid'])."'")->save($data)){
				$uploadSuccess    =    1;
                //$ajaxMsg  =  $merchandiseModel->getLastSql();
			}else{
				$uploadSuccess =  0;
                $ajaxMsg  =  $merchandiseModel->getLastSql();
			}
        }else{
                $uploadSuccess =  0;
               // $ajaxMsg  =  "图片更新失败！";
        }        
    	if(isset($_POST['_uploadResponse']) ) {
            // Ajax方式上传参数信息
            $info = Array();
            $info['states']  =  $uploadSuccess;
            $info['message']   = $ajaxMsg;
            //设置Ajax上传返回元素Id
            if(isset($_POST['_uploadResponse'])) {
                //设置Ajax上传响应方法名称
                $info['uploadResponse'] =  $_POST['_uploadResponse']; 
            }
             $info['data'] = $data;
            $this->ajaxUploadResult($info);
        }
	}
	
	protected function ajaxUploadResult($info) 
    {
        // Ajax方式附件上传提示信息设置
        // 默认使用mootools opacity效果
        //$show   = '<script language="JavaScript" src="'.WEB_PUBLIC_URL.'/Js/mootools.js"></script><script language="JavaScript" type="text/javascript">'."\n";    
		$show   = '<script language="JavaScript" type="text/javascript">'."\n";
        $show  .= ' var parDoc = window.parent.document;';    
        //if(isset($info['uploadResponse'])) {
            $show  .= 'window.parent.'.'uploadComplete'.'(\''.json_encode($info['data']).'\',"'.$info['message'].'","'.$info['states'].'");';
       // }
        $show .= "\n".'</script>';   
		header("Content-Type:text/html; charset=utf-8");
		exit($show);
        //return ;
    }
	/*//删除图片
    public function deleteImg(){
    	$this->validate();
    	if(!empty($_POST['index']) && !empty($_POST['id'])){
    		$merchandiseModel = D("merchandise");
	        $data = Array();
	        $data["mcd_subimage".$_POST['index']] = '';
	    	if(false!==$merchandiseModel->where("mcd_id='".trim($_POST['id'])."'")->save($data)){
				$this->ajaxReturn($_POST['index'],'图片删除成功！',1);
			}else{
				$ajaxMsg  =  $merchandiseModel->getDbError();
				$this->ajaxReturn($_POST['index'],$ajaxMsg,0);
                
			}	
    	}else{
    		$this->ajaxReturn("",'参数问题删除图片失败，请重试！',0);
    	}
    }*/
    
    //编辑信息
    public function merchandise_edit(){
    	$this->validate();
		$this->getmerchandise("merchandise_edit");
    }
    
    public function merchandise_edit_sub(){
        $this->validate();
        import("@.ORG.Input");
        $merchandiseModel = D("merchandise");
        if(!empty($_POST['id'])){
            $id = Input::getVar($_POST['id']);
            $data['mcd_detail'] = Input::getVar($_POST['content']);
            if(false!==$merchandiseModel->where("mcd_id = ".$id)->save($data)){
                $this->redirect('UserAdmin/merchandise_detail/id/'.$id);
            }else{
                echo "修改失败，原因：".$Store->getDbError();
            }
        }else{
            echo "参数错误";
        }
    }
    
    public function updateOpenOrClose(){
    	$this->validate();
        if(!empty($_POST['id'])){
            import("@.ORG.Input");
    		$merchandiseModel = D("merchandise");
    		$data['mcd_detailflag'] = Input::safeHtml(Input::addSlashes(Input::getVar($_POST['mcd_detailflag'])));
            $merchandiseModel->where("mcd_id='".trim($_POST['id'])."'")->save($data);
            $this->ajaxReturn("",$merchandiseModel->getLastsql(),0);
        }else{
        	$this->ajaxReturn("",$merchandiseModel->getLastsql(),0);
        }    
    }
    
    //充值
    public function recharge(){
    	$this->validate();
    	if(!empty($_POST['id']) && !empty($_POST['password'])){
    		$suserModel = D('suser');
    		$cardsModel = D('cards');
    		$rechargeModel = D('recharge');
    		$resultCards = $cardsModel->where("card_id='".$_POST['id']."' and card_password='".$_POST['password']."'")->find();
    		if($resultCards!==null){
    			if($resultCards['card_static']=='2'){
    				$msg="卡号无效，该卡号已被使用！";
    			}else{
    				$cardsData['card_static']='2';
    				$cardsData['card_userid']=$_SESSION['suser']['account'];
    				$cardsModel->startTrans();
    				if(false!==$cardsModel->where("card_id='".$_POST['id']."'")->save($cardsData)){
    					$rechargeData["recharge_mid"]=$_SESSION['suser']['store_id'];
    					$rechargeData["recharge_paidcard"]=$_POST['id'];
    					$rechargeData["recharge_paidamount"]=$resultCards['card_amount'];
    					$rechargeData["recharge_paiddate"]=date("Y-m-d H:i:s");
    					if(false!==$rechargeModel->add($rechargeData)){
    						$resultSuser = $suserModel->where("suser_id='".$_SESSION['suser']['account']."'")->find();
    						if($resultSuser){
    							$suserData['suser_pointcard']=intval($resultSuser['suser_pointcard'])+intval($resultCards['card_amount']);
    							$suserData['suser_totlepointcard']=intval($resultSuser['suser_totlepointcard'])+intval($resultCards['card_amount']);
    							if(false!==$suserModel->where("suser_id='".$_SESSION['suser']['account']."'")->save($suserData)){
    								$cardsModel->commit();
    							}else{
    								$cardsModel->rollback();
    								$msg="充值失败，请重试！";
    							}
    						}else{
    							$cardsModel->rollback();
    							$msg="充值失败，请重试！";
    						}
    						
    					}else{
    						$cardsModel->rollback();
    						$msg="充值失败，请重试！";
    					}
    				}else{
    					$cardsModel->rollback();
    					$msg="充值失败，请重试！";
    				}
    			}
    		}else{
    			$msg="卡号或密码不正确！";
    		}
    	}else{
    		$msg="    ";
    	}
    	
    	if(!empty($msg)){
    		$this->assign('msg',$msg);
    		$this->assign("data",$_POST);
    		$this->display();
    	}else{
    		$this->redirect('UserAdmin/index');
    	}
    }
    
    //修改资料
     public function edit(){
     	$this->validate();
     	$suserModel = D("suser");
    	$storeModel = D("store");
    	$vo = $storeModel->join("suser on suser.suser_id = store.store_mid")
		->where("suser.suser_id='".$_SESSION['suser']['account']."'")->find();
		$this->assign('vo',$vo);
        $this->assign("pointcard", $vo['suser_pointcard']);
     	$this->display();
     }
     
    public function editMaterial(){
    	$this->validate();
    	$suserModel = D("suser");
    	$storeModel = D("store");
    	if($_POST["suser_password"]!=$_POST["password_hidden"]){
    		$dataSuser["suser_password"]   =  md5(trim($_POST["suser_password"]));
    	}
		$dataSuser["suser_realname"]   =  trim($_POST["suser_realname"]);
		$dataSuser["suser_idnumber"]   =  trim($_POST["suser_idnumber"]);
		$dataSuser["suser_email"] 	   =  trim($_POST["suser_email"]);
		$dataSuser["suser_qq"] 		   =  trim($_POST["suser_qq"]);
		$dataSuser["suser_tel"]        =  trim($_POST["suser_tel"]);
		$suserModel->startTrans();
		//$suserModel->create($dataSuser);
		if(false!== $suserModel->where("suser_id='".$_POST["suser_id"]."'")->save($dataSuser)){
				$dataStore["store_id"]		 =  trim($_POST["store_id"]);;
				$dataStore["store_type"]     =  trim($_POST["store_type"]);
				$dataStore["store_address"]  =  trim($_POST["store_address"]);
				$dataStore["store_mid"]   	 =  trim($_POST["suser_id"]);
				$dataStore["store_static"]   =  0;
				$dataStore["store_recommend"]   =  0;
				$dataStore["store_name"]     =  trim($_POST["store_name"]);
				$dataStore["store_category"] =  trim($_POST["store_category"]);
                $dataStore["store_keyword"] =  trim($_POST["store_keyword"]);
			if(false!==$addStoreResult = $storeModel->where("store_id='".$_POST["store_id"]."'")->save($dataStore)){
                //echo $storeModel->getLastSql();
				$suserModel->commit();
				$this->redirect('UserAdmin/index');
			}else{
				$suserModel->rollback();
				$msg="资料修改失败， 请重试！";
				$this->assign('msg',$msg);
				$this->display('edit');
			}			
		}
		else{
			$suserModel->rollback();
			$msg="资料修改失败， 请重试！";
			$this->assign('msg',$msg);
			$this->display('edit');
		}

    }
}

//商品系列类
class series{	
	public $seriesStr=array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
}
?>